package com.qb.hotelTV.Utils;

import android.os.Handler;
import android.os.Looper;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * 线程池管理器
 * 替代Timer/TimerTask，提供更好的资源管理和性能
 */
public class ThreadPoolManager {
    private static final String TAG = "ThreadPoolManager";
    
    // 单例实例
    private static volatile ThreadPoolManager instance;
    
    // 定时任务线程池
    private ScheduledExecutorService scheduledExecutor;
    
    // 主线程Handler
    private Handler mainHandler;
    
    private ThreadPoolManager() {
        scheduledExecutor = Executors.newScheduledThreadPool(2);
        mainHandler = new Handler(Looper.getMainLooper());
    }
    
    public static ThreadPoolManager getInstance() {
        if (instance == null) {
            synchronized (ThreadPoolManager.class) {
                if (instance == null) {
                    instance = new ThreadPoolManager();
                }
            }
        }
        return instance;
    }
    
    /**
     * 在主线程执行任务
     */
    public void runOnUiThread(Runnable task) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            task.run();
        } else {
            mainHandler.post(task);
        }
    }
    
    /**
     * 延迟在主线程执行任务
     */
    public void runOnUiThreadDelayed(Runnable task, long delayMillis) {
        mainHandler.postDelayed(task, delayMillis);
    }
    
    /**
     * 移除主线程任务
     */
    public void removeUiThreadTask(Runnable task) {
        mainHandler.removeCallbacks(task);
    }
    
    /**
     * 执行单次延迟任务
     */
    public ScheduledFuture<?> schedule(Runnable task, long delay, TimeUnit unit) {
        return scheduledExecutor.schedule(task, delay, unit);
    }
    
    /**
     * 执行周期性任务（固定延迟）
     */
    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long initialDelay, 
                                                     long delay, TimeUnit unit) {
        return scheduledExecutor.scheduleWithFixedDelay(task, initialDelay, delay, unit);
    }
    
    /**
     * 执行周期性任务（固定频率）
     */
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long initialDelay, 
                                                  long period, TimeUnit unit) {
        return scheduledExecutor.scheduleAtFixedRate(task, initialDelay, period, unit);
    }
    
    /**
     * 安全的周期性任务 - 在主线程执行
     */
    public ScheduledFuture<?> scheduleOnUiThread(Runnable task, long delay, TimeUnit unit) {
        return schedule(() -> runOnUiThread(task), delay, unit);
    }
    
    /**
     * 安全的周期性任务 - 在主线程执行（固定延迟）
     */
    public ScheduledFuture<?> scheduleOnUiThreadWithFixedDelay(Runnable task, long initialDelay, 
                                                               long delay, TimeUnit unit) {
        return scheduleWithFixedDelay(() -> runOnUiThread(task), initialDelay, delay, unit);
    }
    
    /**
     * 取消任务
     */
    public void cancelTask(ScheduledFuture<?> future) {
        if (future != null && !future.isCancelled()) {
            future.cancel(true);
        }
    }
    
    /**
     * 清理所有任务
     */
    public void shutdown() {
        if (scheduledExecutor != null && !scheduledExecutor.isShutdown()) {
            scheduledExecutor.shutdown();
            try {
                if (!scheduledExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
                    scheduledExecutor.shutdownNow();
                }
            } catch (InterruptedException e) {
                scheduledExecutor.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
        
        if (mainHandler != null) {
            mainHandler.removeCallbacksAndMessages(null);
        }
    }
    
    /**
     * 是否已关闭
     */
    public boolean isShutdown() {
        return scheduledExecutor == null || scheduledExecutor.isShutdown();
    }
    
    /**
     * 重新初始化（在应用恢复时使用）
     */
    public void reinitialize() {
        if (isShutdown()) {
            scheduledExecutor = Executors.newScheduledThreadPool(2);
            mainHandler = new Handler(Looper.getMainLooper());
        }
    }
} 